package com.kun.kunkunmall.cart.interceptor;


import com.kun.common.constant.AuthServerConstant;
import com.kun.common.constant.CartConstant;
import com.kun.common.vo.MemberRespVo;
import com.kun.kunkunmall.cart.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberRespVo attribute = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoVo userInfoVo = new UserInfoVo();
        if (attribute != null) {
            // 用户已经登录
            userInfoVo.setUserId(attribute.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoVo.setUserKey(cookie.getValue());
                    userInfoVo.setTempUser(true);
                }
            }
        }

        // 如果没有临时用户，一定分配一个临时用户
        if (StringUtils.isEmpty(userInfoVo.getUserKey())) {
            // 第一次进来临时用户是空的
            String uuid = UUID.randomUUID().toString();
            userInfoVo.setUserKey(uuid);
        }
        // 目标方法执行之前
        threadLocal.set(userInfoVo);
        return true;
    }

    /**
     * 业务执行完成之后，让浏览器保存一个名为user-key的cookie
     *
     * @param request      current HTTP request
     * @param response     current HTTP response
     * @param handler      the handler (or {@link}) that started asynchronous
     *                     execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     *                     (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 判断当前有没有名字为user-key的cookie
        if (!threadLocal.get().getTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
            // 设置cookie的作用域
            cookie.setDomain("kunkunmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
